﻿#建议保存编码为：bom头 + utf8
#

param
(
	[parameter(Mandatory = $true)]
	[ValidateNotNullOrEmpty()]
	[Alias("upstream_ip")][string]$上游ip,

	[parameter(Mandatory = $true)]
	[ValidateNotNullOrEmpty()]
	[Alias("upstream_port")][UInt16]$上游端口,

	[ValidateNotNullOrEmpty()]
	[Alias("upstream_weight")][byte]$上游权重 = 1,

	[parameter(Mandatory = $true)]
	[ValidateNotNullOrEmpty()]
	[Alias("name")][string]$上游名字,

	[string]$协议 = "http",

	[string]$endpoints , #后面不要有/

	[string]$username = '',

	[string]$password = '', 
	
	[string]$pfx
)

if ( ($null -eq $endpoints) -or ($endpoints -eq '') )
{
	if ( ($null -eq $global:endpoints) -or ($global:endpoints -eq '') )
	{
		Write-Error '错误：endpoints值错误。返回码 21'
		exit 21
	}
	else
	{
		$endpoints = $global:endpoints
	}
}

$body = @{
	id             = $id = "{0}" -f $(& "${PSScriptRoot}/uint64随机数.ps1")
	name           = $上游名字
	type           = "roundrobin"
	timeout        = @{ connect = 9; send = 9; read = 9 }
	retries        = 2
	retry_timeout  = 9
	scheme         = $协议
	#nodes          = @{ "${上游ip}:${上游端口}" = ${上游权重} }
	nodes          = ,@{host = $上游ip ; port = $上游端口 ; weight = $上游权重 }
	pass_host      = "pass"
	keepalive_pool = @{ idle_timeout = 60; requests = 1000; size = 320 }
	create_time    = $private:ct = [int](New-TimeSpan -Start "1/1/1970").TotalSeconds - 28800
	update_time    = $private:ct + 1
} | ConvertTo-Json -Depth 5

Write-Verbose $body
# exit

$k = "/apisix/upstreams/{0}" -f $id

if ($pfx)
{
	if ($PSVersionTable.psversion.major -lt 7)
	{
		Write-Error '错误：win7需要powershell v7.2.x。win10及以上需要powershell v7.4.x。返回码993'
		exit 993
	}

	try
	{
		$null = & "${PSScriptRoot}/put-k8sKey.ps1" -endpoints $endpoints -pfx $pfx -k $k -v $body
		Write-Host "信息：添加上游成功，上游id：" -ForegroundColor Green
		return $id
	}
	catch
	{
		Write-Error '错误：添加上游失败，返回码1'
		exit 1
	}
}
else
{
	try
	{
		$null = & "${PSScriptRoot}/put-etcdKey.ps1" -endpoints $endpoints -username $username -password $password -k $k -v $body
		Write-Host "信息：添加上游成功，上游id：" -ForegroundColor Green
		return $id
	}
	catch
	{
		Write-Error '错误：添加上游失败，返回码1'
		exit 1
	}
}

<#
{
  "nodes": [
    {
      "host": "192.168.168.8",
      "port": 9082,
      "weight": 2
    }
  ],
  "retries": 2,
  "timeout": {
    "connect": 9,
    "send": 9,
    "read": 9
  },
  "type": "roundrobin",
  "scheme": "http",
  "pass_host": "pass",
  "name": "测试上游",
  "keepalive_pool": {
    "idle_timeout": 60,
    "requests": 1000,
    "size": 320
  },
  "retry_timeout": 9
}

#>

